//
//  SCPictureView.swift
//  weibo
//
//  Created by 阿城 on 15/12/11.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

let cellMargin:CGFloat = 5
let cellWidth: CGFloat = CGFloat(Int((kScreenWidth - CGFloat(2)*(kMargin + cellMargin)) / 3))
let collectionCellReuseId = "collectionCellReuseId"

class SCPictureView: UICollectionView{
    
    var picsUrl: [SCPictureInfo]?{
        didSet{
            picNum = picsUrl?.count ?? 0
            lab.text = "\(picNum)"
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(setupSize())
            }
            reloadData()
        }
    }
    private var picNum: Int = 0
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupCollectionView()
        backgroundColor = UIColor(white: 0.95, alpha: 1)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupSize()->CGSize{
        
        addSubview(lab)
        lab.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        
        if picNum != 0{
            let colNum: Int = picNum == 4 ? 2 : min(picNum, 3)
            let rowNum: Int = (picNum - 1) / 3 + 1
            let sizeW = CGFloat(colNum) * cellWidth + CGFloat(colNum - 1) * cellMargin
            let sizeH = CGFloat(rowNum) * cellWidth + CGFloat(rowNum - 1) * cellMargin
            return CGSize(width: sizeW, height: sizeH)
        }else{
            return CGSizeZero
        }
    }
    
    private func setupCollectionView(){
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        dataSource = self
        delegate = self
        registerClass(SCPicCollectionViewCell.self, forCellWithReuseIdentifier: collectionCellReuseId)
    }
    
    private lazy var lab: UILabel = UILabel(titleText: "", fontSize: 40)
}

extension SCPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picNum
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellReuseId, forIndexPath: indexPath) as! SCPicCollectionViewCell
        cell.picUrl = picsUrl![indexPath.item].thumbnail_pic
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        // 图片张数
        browser.imageCount = picsUrl?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
    }
}

extension SCPictureView: SDPhotoBrowserDelegate {
    //    - (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
    //    {
    //    return [self.subviews[index] currentImage];
    //    }
    //
    
    // 返回对应 index 的图片 --> 在我们这种情况下,是返回 对应 item 的 cell 里面的图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 设置 indexPath
        let index = NSIndexPath(forItem: index, inSection: 0)
        // 通过 indexPath 获取到其对应的 cell
        if let cell = self.cellForItemAtIndexPath(index) as? SCPicCollectionViewCell {
            return cell.imageView.image
        }
        return nil
    }
    
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = picsUrl![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlString)
        
    }
    
    
    //
    //    // 返回高质量图片的url
    //    - (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
    //    {
    //    NSString *urlStr = [[self.photoItemArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    //    return [NSURL URLWithString:urlStr];
    //    }
    
    
    
    
}